package paylayer

import (
	"strconv"
	"dhfshop/models/shopping"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"dhfshop/models/member"
)
//充值支付消息通知
func ChargeNotify(payNotify *CommonPayNotify) (err error) {
	var (
		srcAccount   *member.Account
	)
	orderId, _:= strconv.ParseInt(payNotify.OrderId, 10, 64)
	balanceLog, err := member.GetBalanceLogByOuterNo(payNotify.OrderId)
	if err != nil {
	    beego.Debug("GetBalanceLogByOuterNo:", err.Error())
	    return
	}  
	if _, err = shopping.GetPaymentListByOrderId(orderId); err == orm.ErrNoRows {
		_, err = shopping.AddPaymentByPayMsg(balanceLog.PartnerId,balanceLog.StoreId,balanceLog.MemberId,
		                 orderId,2,"1",payNotify.TransactionId,payNotify.FeeType,
						 payNotify.AppId,payNotify.MchId,"",payNotify.SrcMessage,
						 payNotify.TotalFee,payNotify.CashFee,payNotify.CouponFee,payNotify.MchTypeId)			
		if err != nil {
			beego.Debug(err.Error())
		}			
	}
	if payNotify.TotalFee == balanceLog.IncBalance {
	    
		sendChargeSuccessMsg(balanceLog.PartnerId,balanceLog.StoreId,balanceLog.MemberId,orderId,payNotify.TotalFee)
		balanceLog.State = 1
		if err = member.UpdateBalanceLogById(balanceLog, "state"); err != nil {
			beego.Debug("UpdateBalanceLogById:", err.Error())
		}
		balanceLog.CouponFee = payNotify.CouponFee
		member.UpdateBalanceLogCouponFee(balanceLog)
		srcAccount, err = member.GetAccountById(balanceLog.MemberId)
		if err != nil {
			beego.Debug("GetAccountById:", err.Error())
			return
		}
		if balanceLog.Present > 0 {
			srcAccount.Balance += payNotify.TotalFee
			srcAccount.Present += balanceLog.Present
			srcAccount.TotalPresent += balanceLog.Present
			if err = member.UpdateAccountById(srcAccount, "balance", "present", "total_present"); err != nil {
				beego.Debug("UpdateAccountById:", err.Error())
				return
			}
		} else {
			srcAccount.Balance += payNotify.TotalFee
			if err = member.UpdateAccountById(srcAccount, "balance"); err != nil {
				beego.Debug("UpdateAccountById:", err.Error())
				return
			}
		}
	} else {
		beego.Debug("充值金额不符合")
	}
	return
}
